package org.amj.wn.jamaat;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.amj.wn.jamaat.Jamaat.JamaatProperty;

@SuppressWarnings("serial")
public class JamaatServiceOperations extends HttpServlet {

	enum Operation {
		CREATE, DELETE, MODIFY;

	}

	class OperationInfo {
		private final String jamaatCode;
		private final String name;
		private final Operation operation;
		private OperationInfo(String jamaatCode, String passCode,
				Operation operation) {
			this.jamaatCode = jamaatCode;
			this.name = passCode;
			this.operation = operation;
		}
		
		public String getJamaatCode() {
			return jamaatCode;
		}
		public String getName() {
			return name;
		}
		public Operation getOperation() {
			return operation;
		}
		
		

	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		
		
		OperationInfo opInfo = getOperationInfo(req);
		
		boolean result = true;
		if(opInfo != null) {
			switch(opInfo.getOperation()) {
			case CREATE:
				result = Jamaat.createOrUpdate(opInfo.jamaatCode, opInfo.name);
				break;
			case DELETE:
				Jamaat.delete(opInfo.jamaatCode);
				break;
			case MODIFY:
				result = Jamaat.modify(opInfo.jamaatCode, opInfo.name);
				break;
			}
		}		
		
		if(result)
			resp.sendRedirect("/admin/menu.jsp?r=2");
		else 
			resp.sendRedirect("/admin/menu.jsp?r=1");
	}

	private OperationInfo getOperationInfo(HttpServletRequest req) {
		String operation = req.getParameter("opt");
		
		Operation opr = null;
		try {
			opr = Operation.valueOf(operation);
		}catch(Exception exp) { return null;}
		
		return new OperationInfo(req.getParameter(JamaatProperty.jamaatCode.name()), 
				req.getParameter(JamaatProperty.name.name()), opr);
	}

}
